package com.vains.service.impl;

import com.vains.client.AuthClient;
import com.vains.service.IAuthService;
import com.vains.system.model.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Service
@AllArgsConstructor
public class AuthServiceImpl implements IAuthService {

    private final AuthClient authClient;

    @Override
    public Boolean hasAuth() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(requestAttributes, "servlet请求和HTTP会话作用域访问对象获取失败");
        // 获取请求的路径
        String requestURI = requestAttributes.getRequest().getRequestURI();
        // 获取access_token参数
        String accessToken = requestAttributes.getRequest().getParameter("access_token");
        Result<Boolean> result  = authClient.hasAuth(requestURI, accessToken);
        if (result == null) {
            log.warn("调用auth服务失败!");
            return Boolean.FALSE;
        }
        if (!result.getSuccess()) {
            log.warn(result.getMessage());
            return Boolean.FALSE;
        }
        return result.getData();
    }
}
